package com.hoperun.checkcloth.ui

import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hoperun.checkcloth.R
import com.hoperun.checkcloth.activity.StuffCheckMainActivity
import com.hoperun.checkcloth.databinding.StuffCheckLoginActivityBinding
import com.hoperun.checkcloth.ui.dialog.SimpleDialog
import com.hoperun.checkcloth.util.hideSoftInput
import com.hoperun.checkcloth.view.WaitDialog
import com.hoperun.checkcloth.viewmodel.StuffCheckLoginViewModel

/***
 *  原材料检验录入登录界面
 */
class StuffCheckLoginActivity : AppCompatActivity() {
    private lateinit var viewModel: StuffCheckLoginViewModel
    private lateinit var binding: StuffCheckLoginActivityBinding
    private lateinit var loading: WaitDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this)[StuffCheckLoginViewModel::class.java]
        binding = DataBindingUtil.setContentView(this, R.layout.stuff_check_login_activity)
        loading = WaitDialog(this)
        setupBindings()
        setupViewModel()
    }

    private fun setupBindings() {
        binding.etPassword.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                viewModel.login(binding.etAccount.text.toString(), binding.etPassword.text.toString())
                hideSoftInput(v)
                return@setOnEditorActionListener true
            }
            false
        }
    }

    private fun setupViewModel() {
        binding.vm = viewModel

        viewModel.dialogMessage.observe(this, { msgRes ->
            SimpleDialog.newInstance(getString(msgRes)).show(supportFragmentManager, "SimpleDialogTip")
        })
        viewModel.navigation.observe(this, {
            startActivity(Intent(this, StuffCheckMainActivity::class.java))
        })
        viewModel.loading.observe(this, { show ->
            if (show) {
                loading.show()
            } else {
                loading.dismiss()
            }
        })
    }

}